//
//  EOCAutoDictionary.m
//  Test
//
//  Created by 杨德龙 on 2017/3/14.
//  Copyright © 2017年 HipalSports. All rights reserved.
/*
    CALayer 类就用了
 */

#import "EOCAutoDictionary.h"
#import <objc/runtime.h> 


@interface EOCAutoDictionary()

@property (nonatomic,strong)NSMutableDictionary *backingStore;

@end

@implementation EOCAutoDictionary


@dynamic string,number,date,opaqueObject;


- (instancetype)init
{
    self=[super init];
    if (self) {
        
        // 初始化一个
        _backingStore=[NSMutableDictionary new];
    }
    return self;
}

#pragma mark ----  runtime 


/**
 使用  resoveInstanceMethod 来解决 @dynamic 属性

 @param sel sel description
 @return return value description
 */
+ (BOOL)resolveInstanceMethod:(SEL)sel
{
    NSString *selectorString=NSStringFromSelector(sel);
    
    if ([selectorString hasPrefix:@"set"])
    {
        class_addMethod(self, sel, (IMP)autoDictionarySetter, "v@:@");
    }
    else
    {
        class_addMethod(self, sel, (IMP)autoDictionaryGetter,"@@:");
    }
    
    return YES;
}

void  autoDictionarySetter(id self,SEL _cmd,id value)
{
    EOCAutoDictionary *typedSelf=(EOCAutoDictionary *)self;
    NSMutableDictionary *backingStore=typedSelf.backingStore;
    NSString *selectorString=NSStringFromSelector(_cmd);
    NSMutableString *key=[selectorString mutableCopy];
    
    // remove the ':' at the end
    [key  deleteCharactersInRange:NSMakeRange(key.length-1, 1)];
    // remove the 'set' prefix
    [key  deleteCharactersInRange:NSMakeRange(0, 3)];
    //
    NSString *lowercaseFirstChar=[[key substringToIndex:1] lowercaseString];
    [key  replaceCharactersInRange:NSMakeRange(0, 1) withString:lowercaseFirstChar];
    //
    if (value) {
        [backingStore setObject:value forKey:key];
    }else{
        [backingStore removeObjectForKey:key];
    }
    
}


id  autoDictionaryGetter(id  self,SEL _cmd)
{
    // Get the backing store from the object
    EOCAutoDictionary *typedSelf=(EOCAutoDictionary *)self;
    NSMutableDictionary *backingStore=typedSelf.backingStore;
    
    // the key is simply the selector name
    NSString *key=NSStringFromSelector(_cmd);
    
    // return the  key
    return [backingStore objectForKey:key];
    
    
}





@end














































